#!/usr/bin/python2.5
"""
    Googbus Calendar - Uses Googbus and provides calendar UI to Google
    Calendar.
    
    Copyright (C) 2008  Matti Raty

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/.
"""


import gtk
import hildon
import time
import osso
import dbus

from googbus import googuser

class AddNewEventDlg(gtk.Dialog):
    """
    Dialog for adding new events to calendar
    """
    def __init__(self, modal=gtk.TRUE):
        gtk.Dialog.__init__(self, "Add new event")

        """
        Event title entries
        """
        title_hbox = gtk.HBox(False, 0)
        
        title_label = gtk.Label()
        title_label.set_markup("Title ")
        title_label.set_alignment(0, 0)
        title_label.show()
        title_entry = gtk.Entry()
        title_entry.show()
        
        title_hbox.pack_start(title_label, False, False, 0)
        title_hbox.pack_start(title_entry)
        title_hbox.show()

        self.vbox.pack_start(title_hbox, True, True, 0)
        
        """
        Location entries
        """
        
        loc_hbox = gtk.HBox(False, 0)
        
        loc_label = gtk.Label()
        loc_label.set_markup("Location ")
        loc_label.set_alignment(0, 0)
        
        loc_label.show()
        loc_entry = gtk.Entry()
        loc_entry.show()
        
        loc_hbox.pack_start(loc_label, False, False, 0)
        loc_hbox.pack_start(loc_entry)
        loc_hbox.show()

        self.vbox.pack_start(loc_hbox, True, True, 0)
        
        """
        Start and end time entries
        """
        start_label = gtk.Label()
        start_label.set_markup("Start time")
        start_label.set_alignment(0, 0)
        start_label.show()
        
        end_label = gtk.Label()
        end_label.set_markup("End time")
        end_label.set_alignment(0, 0)
        end_label.show()
        
        start_date = hildon.DateEditor()
        start_date.show()
        
        end_date = hildon.DateEditor()
        end_date.show()
        
        start_time = hildon.TimeEditor()
        start_time.show()
        
        end_time = hildon.TimeEditor()
        end_time.show()
        
        tbox = gtk.Table(4, 2, False)
        
        tbox.attach(start_label, 0, 1, 0, 1)
        tbox.attach(start_time, 1, 2, 1, 2)
        tbox.attach(start_date, 0, 1, 1, 2)
        
        tbox.attach(end_label, 0, 1, 2, 3)
        tbox.attach(end_time, 1, 3, 3, 4)
        tbox.attach(end_date, 0, 1, 3, 4)            
        
        tbox.show()
        self.vbox.pack_start(tbox, True, True, 0)
        
        self.vbox.set_spacing(20)
        
        """
        Action buttons
        """
        event_info = (title_entry, loc_entry, 
                      start_date, start_time,
                      end_date, end_time)
        btn_add_event = gtk.Button("Add event")
        btn_add_event.connect("clicked", self.add_event_dlg_add, self.window, event_info)
        btn_add_event.show()
        
        btn_cancel = gtk.Button("Cancel")
        btn_cancel.connect("clicked", self.add_event_dlg_cancel, self.window)
        btn_cancel.show()

        self.action_area.pack_start(btn_add_event, True, True, 0)
        self.action_area.pack_start(btn_cancel, True, True, 0)
        
        self.ret = False
        
    def run(self):
        gtk.Dialog.run(self)
        
        return self.ret
        
    def set_calendar_iface(self, calendar_iface):                
        self.calendar_iface = calendar_iface
        
        
    def set_osso_context(self, osso_context):
        self.osso_context = osso_context
        
        
    def add_event_dlg_cancel(self, widget, event):
        """
        Cancels dialog
        """
        self.ret = False
        self.hide() 
        self.destroy()
        
        
    def add_event_dlg_add(self, widget, event, data):
        """
        Adds event to Google calendar
        
        Parameter data is tuple_
        (title widget, location widget, start_date widget, start_time widget 
        end_date widget, end_time widget, dialog)
        """
        #Format needs to be %Y-%m-%dT%H:%M:%S.000<TIMEZONE>
        TIME_FORMAT = "%s-%s-%sT%s:%s:00.000" + self.timezone()
        
        sdate = data[2].get_date() 
        stime = data[3].get_time()
        start = TIME_FORMAT % (sdate[0], self.trim(sdate[1]), self.trim(sdate[2]),
                               self.trim(stime[0]), self.trim(stime[1]))
        
        edate = data[4].get_date()
        etime = data[5].get_time()
        end = TIME_FORMAT % (edate[0], self.trim(edate[1]), self.trim(edate[2]),
                             self.trim(etime[0]), self.trim(etime[1]))
        
        note = osso.SystemNote(self.osso_context)
        result = note.system_note_infoprint("Adding calendar entry..")
        
        event_ret = self.calendar_iface.InsertNewEvent(data[0].get_text(), 
                                                       "", data[1].get_text(), 
                                                       start, end)
        
        self.ret = True
        self.hide()
        self.destroy()
            
        
    def timezone(self):
        """
        Gets current time zone.
        
        Return Z for time zone 0 or +-xy:00 for other zones
        """
        FORMAT1 = "%s0%s:00" #Timezone is single digit
        FORMAT2 = "%s:00" #Timezone is double digit
        
        if time.daylight == 0:
            zone = -(time.timezone / 60 / 60)
        else:
            zone = -(time.altzone / 60 / 60)
        
        ret = ""
        
        if zone == 0:
            ret = "Z"
        elif zone < 0:
            if zone > -10: 
                ret = FORMAT1 % (str(zone)[0], str(zone)[1])
            else:
                ret = FORMAT2 % (str(zone))
        else:
            if zone < 10: 
                ret =  FORMAT1 % ("+", str(zone))
            else:
                ret = FORMAT2 % ("+" + str(zone))
        
        return ret
    
    
    def trim(self, value):
        """
        Trims date and time values.
        If they are len 1 then zero is added before them
        """
        TRIMMED_FORMAT = "0%s"
        if value < 10:
            return TRIMMED_FORMAT % (value)
        else:
            return value
        


class UserAccountDlg:
    """
    Dialog for setting user account information
    """
    
    def __init__(self, window):
        self.wnd = window
        self.user = googuser.GoogleUser()
        
        
    def run_dialog(self, username = None, password = None):
        """
        Shows dialog
        
        Returns True if account infromation is set, otherwise False
        """
        if username and password:
            dialog = hildon.hildon_login_dialog_new_with_default(self.wnd, 
                                                                 username, 
                                                                 password)
        else:
            dialog = hildon.hildon_login_dialog_new_with_default(self.wnd, "", "")
            
        dialog.set_title("Setup Google account")
        dialog.set_message("Tip: User name is usually email.")
    
        response = dialog.run()
        dialog.hide()
    
        if response == gtk.RESPONSE_OK:
           ret = self.user.write_user_data(dialog.get_username(), dialog.get_password())
        else:
           ret = False
        
        dialog.destroy()
     
        return ret
        